
package com.the9tcat.deliverycoming;

import java.util.ArrayList;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.the9tcat.deliverycoming.data.Configure;
import com.the9tcat.deliverycoming.db.DeliveryDb;
import com.the9tcat.deliverycoming.modle.DeliveryInfo;
import com.the9tcat.deliverycoming.modle.NotificationCenter;
import com.the9tcat.deliverycoming.net.HttpClient;
import com.the9tcat.deliverycoming.util.Logger;

public class MessengerService extends Service {
    /** For showing and hiding our notification. */
   
    public static boolean service_running = false;

    private static String LOG_TAG = "MessengerService";

    public static String START_MSG_SERVICE = "START_MSG_SERVICE";

    @Override
    public void onCreate() {
        service_running = true;
        Logger.d(LOG_TAG, "onCreate");
   
        // // Display a notification about us starting.
        // showNotification();
    }

    @Override
    public void onStart(final Intent intent, int startId) {

        Logger.d(LOG_TAG, "onStart");
        super.onStart(intent, startId);

        new Thread(new Runnable() {
            @Override
            public void run() {

                checkNewTrack();

            }
        }).start();

    };

    private void checkNewTrack() {
        Logger.d(LOG_TAG, "checkNewTrack");
        // DeliveryDb deliveryDb = new DeliveryDb(getApplicationContext());
        DeliveryDb deliveryDb = DeliveryDb.getDb(getApplicationContext());
        //deliveryDb.open();
        ArrayList<DeliveryInfo> deliveryInfos = deliveryDb
                .getDeliveryInTrack(Configure.MODE_UNSIGNED_TRACKLIST);

        for (DeliveryInfo deliveryInfo : deliveryInfos) {
             HttpClient.newInstance()
                    .updateDeliveryDetails(deliveryInfo, null);
             boolean updated = deliveryDb.update(deliveryInfo);
            if (updated) {
                // 提醒用户
                Logger.d("***", "service " + deliveryInfo.getId());
                NotificationCenter nc = NotificationCenter
                        .getNotificationCenter(getApplicationContext());
                nc.showNotification(getText(R.string.track_updated)
                        + deliveryInfo.getName(), deliveryInfo
                        .getLatestStatus(), deliveryInfo.getId());
            }
        }
        //deliveryDb.close();
    }

    @Override
    public void onDestroy() {
        service_running = false;

    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}
